package com.njwb.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    public static final String SECRET = "!njwb~";//密钥
    public static Integer JWT_TIME = 600;//过期时间
    /**
     * 生成JWT Token字符串
     * @param payload 有效负载
     * @return Token字符串
     */
    public static String generateJWT(Map<String,String> payload){
        //固定好头部，也可以缺省不写
        Map header = new HashMap();
        header.put("alg","HS256");
        header.put("typ","JWT");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,JWT_TIME);
        JWTCreator.Builder builder = JWT.create();
        payload.forEach((k,v)->builder.withClaim(k,v));
        return builder.withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET));
    }
    /**
     * 验证JWT
     * @param jwt
     * @return
     */
    public static DecodedJWT verfiyJWT(String jwt){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        return jwtVerifier.verify(jwt);
    }
    /**
     * 获取有效负载信息
     * @param key
     * @param jwt
     * @return
     */
    public static String getPayload(String key,String jwt){
        DecodedJWT decodedJWT = verfiyJWT(jwt);
        return decodedJWT.getClaim(key).asString();
    }
}
